﻿using System;
using System.Linq;
using Microsoft.Win32;

namespace OrbitOne.CRMLyncInfoDashboard.Setup
{
    public class RegistryProvider : IRegistryProvider
    {
        public const string RegistryLocation = @"Software\Microsoft\Communicator\ContextPackages\";
        
        public void SaveConfiguration(LyncExtensionRegistryEntry registryEntry)
        {
            if (IsConfigurationPresent(DashboardInstaller.ApplicationKey))
            {
                DeleteConfiguration(DashboardInstaller.ApplicationKey);
            }

            CreateConfiguration(registryEntry);
        }

        private void CreateConfiguration(LyncExtensionRegistryEntry registryEntry)
        {
            var registryPath = string.Format("{0}{{{1}}}", RegistryLocation, DashboardInstaller.ApplicationKey);
            var registryKey = Registry.CurrentUser.OpenSubKey(registryPath, true) ??
                              Registry.CurrentUser.CreateSubKey(registryPath);

            SetRegistryValues(registryEntry, registryKey);
        }

        private void SetRegistryValues(LyncExtensionRegistryEntry registryEntry, RegistryKey registryKey)
        {
            var properties = registryEntry.GetType().GetProperties().ToList();
            properties.ForEach(property => registryKey.SetValue(property.Name, property.GetValue(registryEntry, null)));
        }

        public void DeleteConfiguration(Guid registryEntryId)
        {
            var registryPath = string.Format("{0}{{{1}}}", RegistryLocation, registryEntryId);
            var registryKey = Registry.CurrentUser.OpenSubKey(registryPath, true);

            if (registryKey != null)
            {
                Registry.CurrentUser.DeleteSubKey(registryPath, true);
            }
        }

        public bool IsConfigurationPresent(Guid registryEntryId)
        {
            var registryPath = string.Format("{0}{{{1}}}", RegistryLocation, registryEntryId);
            var registryKey = Registry.CurrentUser.OpenSubKey(registryPath, true);
            return registryKey != null;
        }
    }
}